const { diaryModels, fileModels } = require("../../models"); //导入数据库操作模块dbModels.js
const mkdir = require("../../lib/mkdir");
//获取日记
exports.getDiaryPage = async (req, res) => {
  try {
    let data = req.body;
    await diaryModels
      .getDiaryPage(data.pageSize, data.nowPage, data.searchTerm)
      .then(async (result) => {
        if (data.count) {
          let c = await diaryModels.getDiaryCount(data.searchTerm);
          count = c[0].count;
        }
        // if (result.length > 0) {
        //   for (let i = 0; i < result.length; i++) {
        //      if(result[i].picture){
        //       // result[i].picture = result[i].picture.split(' ');//将字符串转换为数组的操作
        //       // result[i].picture = JSON.parse(result[i].picture);
        //      }
        //   }
        // }
        res.send({
          code: 200,
          data: result,
          count: count,
        });
      });
  } catch (error) {
    res.send({
      code: 400,
      data: error,
    });
  }
};

//新建日记
exports.addDiary = async (req, res) => {
  try {
    let data = req.body;
    await diaryModels.addDiary(data.value).then((result) => {
      res.send({
        code: 200,
        data: result,
      });
    });
  } catch (error) {
    res.send({
      code: 400,
      data: error,
    });
  }
};

//删除日记
exports.deleteDiary = async (req, res) => {
  try {
    let data = req.body;
    // 删除随笔的图片文件
    if (data.fileUrl.length > 0) {
      await fileModels.deleteFileByPath(data.fileUrl);
      if (typeof data.fileUrl === "string") {
        const filePath = `data/files/${data.fileUrl}`;
        await mkdir.delFiles(filePath);
      } else {
        data.fileUrl.forEach(async (url) => {
          const filePath = `data/files/${url}`;
          await mkdir.delFiles(filePath);
        });
      }
    }
    await diaryModels.deleteDiary(data.diaryId).then((result) => {
      res.send({
        code: 200,
        data: result,
      });
    });
  } catch (error) {
    res.send({
      code: 400,
      data: error,
    });
  }
};
